﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FlexFlow.Runtime;
using FlexFlow.Model;
using FlexFlow.MVC;

namespace FlexFlow.WebAPI.Controllers
{
    /// <summary>
    /// 表示用户登录API控制器
    /// </summary>
    public class UserAPIController : Controller
    {
        /// <summary>
        /// 登录处理模块
        /// </summary>
        /// <param name="acc">
        /// 要登录的账号
        /// </param>
        /// <param name="pwd">
        /// 与登录账号对应的密码
        /// </param>
        /// <param name="forceLogin">
        /// 是否强制登录(on,off)
        /// </param>
        /// <returns>
        /// 登录结果(Json)
        /// </returns>
        public ActionResult Login(string acc, string pwd, string forceLogin = "off")
        {
            OperateResult res = UserManager.Default.Login(acc, pwd, forceLogin == "on");
            if (res.ResultCode == 200)
            {
                Response.Cookies[InProcOnlineUserPool.LoginedUserIdentityKey].Value = res.Tag.ToString();
            }
            return Json(res);
        }
        /// <summary>
        /// 注册处理模块
        /// </summary>
        /// <param name="acc">
        /// 要注册的账号
        /// </param>
        /// <param name="pwd">
        /// 注册密码
        /// </param>
        /// <param name="email">
        /// 注册Email
        /// </param>
        /// <returns>
        /// 注册结果(Json)
        /// </returns>
        public ActionResult Register(string acc, string pwd, string email)
        {
            OperateResult res = UserManager.Default.Register(acc, pwd, email);
            return Json(res);
        }
        /// <summary>
        /// 重命名指定用户
        /// </summary>
        /// <param name="identity">
        /// 用户ID
        /// </param>
        /// <param name="newName">
        /// 新名称
        /// </param>
        /// <returns>
        /// 操作结果
        /// </returns>
        [Auth(AuthType.API)]
        public ActionResult Rename(Guid identity, string newName)
        {
            return Json(UserManager.Default.Rename(identity, newName));
        }
        /// <summary>
        /// 登出具有指定登录信息键的登录用户
        /// </summary>
        /// <param name="key">
        /// 登录用户的登录信息键，由Login函数提供
        /// </param>
        /// <returns>
        /// 登出结果(Json)
        /// </returns>
        [Auth(AuthType.API)]
        public ActionResult Logout(Guid? key = null)
        {
            if (key == null)
            {
                HttpCookie cookie = Request.Cookies[InProcOnlineUserPool.LoginedUserIdentityKey];
                if (cookie == null)
                {
                    return Json(new OperateResult()
                    {
                        ResultCode = 500,
                        Message = "非法操作！"
                    });
                }
                Guid infoid;
                if (Guid.TryParse(cookie.Value, out infoid))
                {
                    return Json(UserManager.Default.Logout(infoid));
                }
                else
                {
                    return Json(new OperateResult()
                    {
                        ResultCode = 500,
                        Message = "参数非法！"
                    });
                }
            }
            else
            {
                OperateResult res = UserManager.Default.Logout((Guid)key);
                return Json(res);
            }
        }
        /// <summary>
        /// 更新用户信息
        /// </summary>
        /// <param name="identity">
        /// 要更新的用户的ID
        /// </param>
        /// <param name="name">
        /// 新名称
        /// </param>
        /// <param name="account">
        /// 新账号
        /// </param>
        /// <param name="email">
        /// 新Email
        /// </param>
        /// <param name="isLock">
        /// 是否锁定
        /// </param>
        /// <returns>
        /// 操作结果
        /// </returns>
        [Auth(AuthType.API)]
        public ActionResult Update(Guid uid, string name = null, string account = null, string email = null, string isLock = "")
        {
            return Json(UserManager.Default.Update(uid, name, account, email, isLock == "on"));
        }
        /// <summary>
        /// 更改指定用户的密码
        /// </summary>
        /// <param name="uid">
        /// 要更改密码的用户ID
        /// </param>
        /// <param name="newPwd">
        /// 要更改的新密码
        /// </param>
        /// <returns>
        /// 操作结果
        /// </returns>
        [Auth(AuthType.API)]
        public ActionResult ChangePassword(Guid uid, string newPwd = null)
        {
            return Json(UserManager.Default.ChangePassword(uid, newPwd));
        }
        /// <summary>
        /// 通过用户姓名查询用户信息(Like模糊查询)
        /// </summary>
        /// <param name="nameLike">
        /// 要查询的用户姓名
        /// </param>
        /// <param name="limit">
        /// 返回结果的限制数量
        /// </param>
        /// <param name="skip">
        /// 返回数据的起始位置
        /// </param>
        /// <returns>
        /// 操作结果
        /// </returns>
        [Auth(AuthType.API)]
        public ActionResult QueryUserByName(string nameLike, int skip = 0, int limit = 10)
        {
            OperateResult res = UserManager.Default.QueryUserByName(nameLike, skip, limit);
            if (res.ResultCode != 200)
            {
                return Json(res);
            }
            else
            {
                List<object> userList = new List<object>();
                foreach (var item in (List<User>)res.Tag)
                {
                    userList.Add(new { name = item.Name, uid = item.Identity, orgName = item.OrganizeName });
                }
                return Json(userList, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 根据指定的用户标识符列表取得用户实体列表
        /// </summary>
        /// <param name="guidList">
        /// 用来取得用户实体的用户Guid列表，以逗号隔开
        /// </param>
        /// <returns>
        /// 操作结果
        /// </returns>
        [Auth(AuthType.API)]
        public ActionResult GetUserListByGuidList(string guidList)
        {
            List<object> userList = new List<object>();
            string[] guids = guidList.Split(',');
            foreach (var guid in guids)
            {
                Guid uid;
                if (Guid.TryParse(guid, out uid))
                {
                    OperateResult res = UserManager.Default.Get(uid);
                    if (res.ResultCode == 200)
                    {
                        User u = res.Tag as User;
                        if (u != null)
                        {
                            userList.Add(new { name = u.Name, uid = u.Identity, orgName = u.OrganizeName });
                        }
                    }
                    else
                    {
                        userList.Add(new { uid = uid, err = res });
                    }
                }
                else
                {
                    userList.Add(new { uid = guid, err = "无效GUID" });
                }
            }
            return Json(OperateResult.SuccessResult(userList));
        }
    }
}
